import { useUserStore } from "@/stores/modules/user";
import { useAuthStore } from "@/stores/modules/auth";
import { LOGIN_URL } from "@/config";
import router from "@/router";
import { ElNotification } from "element-plus";
import { RouteRecordRaw } from "vue-router";

// 引入动态加载的视图组件
const modules = import.meta.glob("@/views/**/*.vue");

// 获取路由配置的函数
const generateRoutes = (routesData) => {
  return routesData.map((route) => {
    const routeConfig: RouteRecordRaw = {
      path: route.path,
      name: route.name,
      component: modules[`/src/views${route.component}.vue`], // 动态导入
      meta: route.meta,
      redirect: route.redirect,
      children: route.children ? generateRoutes(route.children) : [],
    };
    return routeConfig;
  });
};

// 初始化动态路由
export const initDynamicRouter = async () => {
  const userStore = useUserStore();
  const authStore = useAuthStore();

  try {
    // 获取菜单列表 && 按钮权限列表
    await authStore.getAuthMenuList(); // API 请求权限菜单
    await authStore.getAuthButtonList(); // API 请求按钮权限

    // 获取用户的路由权限列表
    const routesData = authStore.authMenuListGet; // 权限菜单

    // 如果用户没有任何菜单权限
    if (!routesData.length) {
      ElNotification({
        title: "无权限访问",
        message: "当前账号无任何菜单权限，请联系系统管理员！",
        type: "warning",
        duration: 3000,
      });
      userStore.setToken("");
      router.replace(LOGIN_URL);
      return Promise.reject("No permission");
    }

    // 动态添加路由
    const generatedRoutes = generateRoutes(routesData);
    generatedRoutes.forEach((route) => {
      if (route.meta.isFull === "T") {
        router.addRoute(route);
      } else {
        router.addRoute("layout", route);
      }
    });
  } catch (error) {
    // 当请求失败时，清除 token 并跳转到登录页面
    userStore.setToken("");
    router.replace(LOGIN_URL);
    return Promise.reject(error);
  }
};
